package com.warning_speed_android;

import java.util.ArrayList;
import java.util.List;

import com.facebook.Session;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.warning_speed_android.gps.AutoSendLocation;
import com.warning_speed_android.gps.GPSTracker;
import com.warning_speed_android.socket.CustomClient;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.os.StrictMode;

public class MainActivity extends ActionBarActivity {

	private static String ADDRESS = "192.168.1.13:9002";
	private Session.StatusCallback sessionStatusCallback;
	private Session currentSession;
	private Button login;
	private Button logout;
	private Button updateLocationButton;
	private Button stopUpdateLocationButton;
	private Spinner spinner;
	private String typeVehicle;

	GPSTracker gps;
	AutoSendLocation autoGps;
	private static int DEFAULT_INTERVAL = 1000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// uiHelper = new UiLifecycleHelper(this, callback);
		setContentView(R.layout.activity_main);

		sessionStatusCallback = new Session.StatusCallback() {

			@Override
			public void call(Session session, SessionState state,
					Exception exception) {
				onSessionStateChange(session, state, exception);

			}
		};

		// login button
		login = (Button) findViewById(R.id.loginButton);
		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				login.setVisibility(View.GONE);
				 connectToFB();
				logout.setVisibility(View.VISIBLE);
				updateLocationButton.setVisibility(View.VISIBLE);
				spinner.setVisibility(View.VISIBLE);

			}
		});

		// logout button
		logout = (Button) findViewById(R.id.logoutButton);
		logout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (currentSession != null) {
					currentSession.closeAndClearTokenInformation();
					logout.setVisibility(View.GONE);
					updateLocationButton.setVisibility(View.GONE);
					spinner.setVisibility(View.GONE);
					login.setVisibility(View.VISIBLE);
				}
			}
		});
		stopUpdateLocationButton = (Button) findViewById(R.id.stopUpdateLocationButton);
		stopUpdateLocationButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				stopSendLocation();
				updateLocationButton.setVisibility(View.VISIBLE);
				stopUpdateLocationButton.setVisibility(View.GONE);
			}
		});

		// publish button
		updateLocationButton = (Button) findViewById(R.id.updateLocationButton);
		updateLocationButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startSendLocation();
				updateLocationButton.setVisibility(View.GONE);
				stopUpdateLocationButton.setVisibility(View.VISIBLE);

			}
		});

		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		// connect
		try {
			CustomClient.instance.connect(ADDRESS);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		addItemsOnSpinner();
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				typeVehicle = parent.getItemAtPosition(pos).toString();
				Toast.makeText(
						parent.getContext(),
						"OnItemSelectedListener : "
								+ typeVehicle,
						Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {

			}
		});
		;

		// init();
		//
	}

	public void connectToFB() {

		List<String> permissions = new ArrayList<String>();
		permissions.add("user_status");

		currentSession = new Session.Builder(this).build();
		currentSession.addCallback(sessionStatusCallback);

		Session.OpenRequest openRequest = new Session.OpenRequest(this);
		openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
		openRequest.setRequestCode(Session.DEFAULT_AUTHORIZE_ACTIVITY_CODE);
		openRequest.setPermissions(permissions);
		currentSession.openForPublish(openRequest);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (currentSession != null) {
			currentSession
					.onActivityResult(this, requestCode, resultCode, data);
		}
	}

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		if (session != currentSession) {
			return;
		}

		if (state.isOpened()) {
			// Log in just happened.
			Toast.makeText(getApplicationContext(), "session opened",
					Toast.LENGTH_SHORT).show();
			String fbtoken = session.getAccessToken();
			try {
				CustomClient.instance.login(fbtoken);
			} catch (Exception e) {
				// TODO: handle exception
				Log.e(MainActivity.class.getSimpleName(), e.getMessage(), e);
			}

		} else if (state.isClosed()) {
			// Log out just happened. Update the UI.
			Toast.makeText(getApplicationContext(), "session closed",
					Toast.LENGTH_SHORT).show();
		}
	}

	public void startSendLocation() {
		if (autoGps == null) {
			autoGps = new AutoSendLocation(MainActivity.this);
			autoGps.setInterval(DEFAULT_INTERVAL);
		}
		autoGps.startWorker();
		Toast.makeText(getApplicationContext(), "start update location",
				Toast.LENGTH_SHORT).show();
	}

	public void stopSendLocation() {
		if (autoGps != null) {
			autoGps.stopWorker();
			Toast.makeText(getApplicationContext(), "stop update location",
					Toast.LENGTH_SHORT).show();
		}

	}

	public void addItemsOnSpinner() {
		spinner = (Spinner) findViewById(R.id.spinner);
		List<String> list = new ArrayList<String>();
		list.add("Choose Your vehicle !");
		list.add("Motorcycle");
		list.add("Car");
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, list);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(dataAdapter);
	}
}
